package com.ylzinfo.ms.qycloud.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.health.DataSourceHealthIndicator;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 *
* 数据源配置（直接通过yml不支持druid的属性）
* @author xuyajie
* @date 2018年12月10日 下午3:08:42
 */
@Configuration
public class DataSourceConfiguration {
	@Bean
	@ConfigurationProperties(prefix="spring.datasource")
	public DataSource getDataSource() {
		return new DruidDataSource();
	}

	@Value("${spring.datasource.validationQuery}")
	private String query;

	/**
	 *
	* 自己初始化数据库健康检查器，自定义数据库健康检查sql
	* @date 2018年12月26日 下午4:20:21
	* @author xuyajie
	* @param dataSource
	* @return
	 */
	@Bean("dbHealthIndicator")
	public HealthIndicator dbHealthIndicator(DataSource dataSource) {
		return new DataSourceHealthIndicator(dataSource, query);
	}

	@Value("${spring.datasource.druidloginname:admin}")
	private String druidloginname;
	@Value("${spring.datasource.druidloginpassword:123456}")
	private String druidloginpassword;
	/**
	* @Description 监控管理界面
	* @Author Rogchen
	* @Date 20:27 2019/1/16
	* @Param []
	* @Return org.springframework.boot.web.servlet.ServletRegistrationBean
	**/
	@Bean
	public ServletRegistrationBean statViewServlet(){
		ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
		servletRegistrationBean.addInitParameter("allow","127.0.0.1");  //设置ip白名单
		servletRegistrationBean.addInitParameter("deny","192.168.0.1");//设置ip黑名单，优先级高于白名单
		//设置控制台管理用户
		servletRegistrationBean.addInitParameter("loginUsername",druidloginname);
		servletRegistrationBean.addInitParameter("loginPassword",druidloginpassword);
		//是否可以重置数据
		servletRegistrationBean.addInitParameter("resetEnable","false");
		return servletRegistrationBean;
	}

	@Bean
	public FilterRegistrationBean statFilter(){
		//创建过滤器
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
		//设置过滤器过滤路径
		filterRegistrationBean.addUrlPatterns("/*");
		//忽略过滤的形式
		filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
		return filterRegistrationBean;
	}
}